import mt from 'moment'
import 'moment/locale/zh-cn'
import qs from 'querystring'
import * as R from 'ramda'
const nodeUrl = require('url')

mt.locale('zh-cn')
export const moment = mt

export const request = window.request
export const requestGBK = window.requestGBK

export function debounce(func, delay = 300) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func(...args)
    }, delay)
  }
}

export function addClass(className, newClass) {
  return className
    ? className
      .split(/\s+/)
      .filter(name => name !== newClass)
      .concat(newClass)
      .join(' ')
    : newClass
}

// 解析query
export function queryParse (str) {
  if (typeof str === 'undefined') str = window.location.href
  if (typeof str !== 'string') return {}
  const search = nodeUrl.parse(str).search
  if (search) {
    return qs.parse(search.substr(1))
  } else {
    return {}
  }
}

export function sleep(delay = 3000) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, delay)
  })
}

export const changeToArr = R.unless(R.is(Array), R.of)
